/**
 * 应用存储
 * 记录菜单展开状态等
 */

import Cookies from 'js-cookie'

const app = {
  state: {
    sidebar: {
      opened: !+Cookies.get('sidebarStatus')
    },
    visitedTabPages: [
      {
        title: '首页',
        name: 'home',
        closable: false
      }
    ],
    cachedViews: [],
    systemTheme: Cookies.get('systemTheme')
  },
  mutations: {
    toggleSidebar: state => {
      if (state.sidebar.opened) {
        Cookies.set('sidebarStatus', 1)
      } else {
        Cookies.set('sidebarStatus', 0)
      }
      state.sidebar.opened = !state.sidebar.opened
    },
    addVisitedTabPages: (state, page) => {
      // 防止当打开首页再添加
      if (page.name === 'home') return
      if (state.visitedTabPages.some(v => v.path === page.path)) return
      // 默认只打开六个tab切换
      if (state.visitedTabPages.length > 8) {
        state.visitedTabPages.splice(1, 1)
      }
      state.visitedTabPages.push(
        {
          name: page.name,
          title: page.meta.title,
          path: page.path,
          query: page.query,
          params: page.params
        })
    },
    delVisitedTabPages: (state, view) => {
      state.visitedTabPages.map((it, index) => {
        if (it.name === view) {
          state.visitedTabPages.splice(index, 1)
        }
      })
    },
    ADD_CACHED_VIEW: (state, view) => {
      if (state.cachedViews.includes(view.name)) return
      if (!view.meta.noCache) {
        state.cachedViews.push(view.name)
      }
    },
    DEL_CACHED_VIEW: (state, view) => {
      const index = state.cachedViews.indexOf(view)
      index > -1 && state.cachedViews.splice(index, 1)
    },
    DELALLVIEWS: (state, view) => {
      state.visitedTabPages.splice(1, state.visitedTabPages.length)
    },
    THEMESYSTEM: (state, theme) => {
      state.systemTheme = theme
    }
  },
  actions: {
    ToggleSideBar ({commit}) {
      commit('toggleSidebar')
    },
    AddVisitedTabPages ({commit}, page) {
      commit('addVisitedTabPages', page)
      commit('ADD_CACHED_VIEW', page)
    },
    DelVisitedTabPages ({commit, state}, page) {
      return new Promise((resolve) => {
        commit('delVisitedTabPages', page)
        commit('DEL_CACHED_VIEW', page)
        resolve([...state.visitedTabPages])
      })
    },
    DELALLVIEWS ({commit}) {
      commit('DELALLVIEWS')
    },
    SETTHEME ({commit, state}, theme) {
      if (Cookies.get('systemTheme') === undefined || Cookies.get('systemTheme') === 'undefined') {
        Cookies.set('systemTheme', '#a22828')
        commit('THEMESYSTEM', '#a22828')
      } else {
        if (theme) {
          Cookies.set('systemTheme', theme)
          commit('THEMESYSTEM', theme)
        } else {
          commit('THEMESYSTEM', Cookies.get('systemTheme'))
        }
      }
    }
  }
}

export default app
